<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { reactive, ref } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { useI18n } from '@/hooks/web/useI18n'
import { Log } from '@/utils/logError'
import { getUserDetailApi } from '@/api/personal-center'
import { useDictStoreWithOut } from '@/store/modules/dict'
import { useUserStoreWithOut } from '@/store/modules/user'
import { cloneDeep } from 'lodash-es'
import { getDepartmentApi, getSelfDepartmentApi } from '@/api/department'
import { listToTree } from '@/utils/tree'

const { t } = useI18n()
const { required, phone, email } = useValidator()
const useDictStore = useDictStoreWithOut()
const useUserStore = useUserStoreWithOut()

const props = defineProps({
  currentId: {
    type: Number,
    default: () => null
  }
})

const rules = reactive({
  username: [required()],
  name: [required()],
  phone: [required(), phone()],
  email: [required(), email()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    return await getFormData()
  }
}

const formSchema = ref<FormSchema[]>([
  {
    field: 'username',
    label: t('personalCenter.username'),
    component: 'Input',
    componentProps: {
      disabled: !!props.currentId
    }
  },
  {
    field: 'name',
    label: t('personalCenter.name'),
    component: 'Input'
  },
  {
    field: 'roles',
    label: t('personalCenter.role'),
    component: 'Select',
    componentProps: {
      multiple: true
    },
    optionApi: async () => {
      return await useDictStore.getCachedDict('role')
    }
  },
  {
    field: 'departmentId',
    label: t('department.parentDeptId'),
    component: 'Cascader',
    componentProps: {
      props: {
        label: 'name',
        value: 'id',
        checkStrictly: true,
        emitPath: false
      }
    },
    optionApi: async () => {
      const result = await (
        useUserStore.userInfo?.roles?.filter((item) => item.code === 'super_admin').length
          ? getDepartmentApi
          : getSelfDepartmentApi
      )()
      return listToTree(result.data || [], { pid: 'parentDeptId' })
    }
  },
  {
    field: 'phone',
    label: t('personalCenter.phone'),
    component: 'Input'
  },
  {
    field: 'email',
    label: t('personalCenter.email'),
    component: 'Input'
  },
  {
    field: 'status',
    label: t('menu.status'),
    component: 'Switch'
  },
  {
    field: 'remark',
    label: t('common.remark'),
    component: 'Input',
    componentProps: {
      type: 'textarea',
      'show-word-limit': true,
      maxlength: 100,
      rows: 4,
      resize: 'none'
    }
  }
])

const getUserDetail = async () => {
  try {
    if (!props.currentId) return await setValues({ status: true })
    const res = await getUserDetailApi(props.currentId)
    const data = cloneDeep(res.data) as any
    data.roles = data.roles?.map((item) => item.code || '') || []
    await setValues(data)
  } catch (error) {
    Log.error('getDepartmentDetail', error)
  }
}
getUserDetail()

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :is-col="false" :schema="formSchema" />
</template>
